package com.cat.dataStructure;

import java.util.ArrayDeque;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string-ii/description/
 * @create 2025/9/9 10:07
 * @since JDK17
 */

public class Solution65 {
    public String removeDuplicates(String str, int k) {
        char[] s = str.toCharArray();
        StringBuilder ans = new StringBuilder(str);
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < ans.length(); i++) {
            if (stack.isEmpty() || (ans.charAt(i - 1) != ans.charAt(i))) {
                stack.push(1);
            } else {    //
                // 上一次相等的数量
                int last = stack.pop() + 1;
                if (last == k) {
                    ans.delete(i - k + 1, i + 1);   // 左闭右开
                    i -= k;
                } else {    // 不够
                    stack.push(last);
                }
            }
        }

        return ans.toString();
    }
}
